package com.example.rabbit;

import com.example.rabbit.enums.DelayEnum;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;


/**
 * @author yangys
 */
@Component
public class DelayMessageSender {

    /**
     * 时间单位 12=分 13=秒
     */
    public static Integer TIME_UNIT;

    public static Integer ORDER_TIMEOUT;

    public static Integer PAY_TIMEOUT;

    public static Integer CONFIRM_TIMEOUT;

    @Value("${time.orderTimeout:5}")
    public void setOrderTimeout(Integer orderTimeout) {
        ORDER_TIMEOUT = orderTimeout;
    }

    @Value("${time.payTimeout:20}")
    public void setPayTimeout(Integer payTimeout) {
        PAY_TIMEOUT = payTimeout;
    }

    @Value("${time.confirmTimeout:30}")
    public void setConfirmTimeout(Integer confirmTimeout) {
        CONFIRM_TIMEOUT = confirmTimeout;
    }

    @Value("${time.unit:12}")
    public void setTimeUnit(Integer unit) {
        TIME_UNIT = unit;
    }

    private static Integer SECOND = 1000;
    private static Integer MINUTE = 1000 * 60;
    private static Integer SURPLUS;

    @Value("${time.surplus:1}")
    public void setSurplus(Integer surplus) {
        SURPLUS = surplus;
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendDelayMsg(String msg, Integer delayTime) {
        rabbitTemplate.convertAndSend(DelayEnum.OTC_ORDER.getExchange(), DelayEnum.OTC_ORDER.getRoutingKey(), msg, a -> {
            a.getMessageProperties().setDelay(TIME_UNIT.equals(Calendar.MINUTE) ? delayTime * MINUTE : delayTime * SECOND);
            return a;
        });

        rabbitTemplate.convertAndSend(DelayEnum.TIME_OUT_NOTIFY.getExchange(), DelayEnum.TIME_OUT_NOTIFY.getRoutingKey(), msg, a -> {
            a.getMessageProperties().setDelay(TIME_UNIT.equals(Calendar.MINUTE) ? (delayTime - SURPLUS) * MINUTE : (delayTime - SURPLUS) * SECOND);
            return a;
        });
    }
}